package com.android.miniskirt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.miniskirt.service.MQTTService;
import com.android.miniskirt.service.getcontacts;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class miniApplication extends Application {
	
	 /** Preference key for account username. */
    public static final String ACCOUNT_USERNAME_KEY = "account_username";
    /** Preference key for account password. */
    public static final String ACCOUNT_PASSWORD_KEY = "account_password";
    /* (non-Javadoc)
	 * @see android.content.ContextWrapper#stopService(android.content.Intent)
	 */
	/** Preference key for status (available, busy, away, ...). */
    public static final String STATUS_KEY = "status";
    /** Preference key for status message. */
    public static final String STATUS_TEXT_KEY = "status_text";
    /** Preference key for the use of a proxy. */
    public static final String PROXY_USE_KEY = "proxy_use";
    /** Preference key for the type of proxy. */
    public static final String PROXY_TYPE_KEY = "proxy_type";
    /** Preference key for the proxy server. */
    public static final String PROXY_SERVER_KEY = "proxy_server";
    /** Preference key for the proxy port. */
    public static final String PROXY_PORT_KEY = "proxy_port";
    /** Preference key for the proxy username. */
    public static final String PROXY_USERNAME_KEY = "proxy_username";
    /** Preference key for the proxy password. */
    public static final String PROXY_PASSWORD_KEY = "proxy_password";
    /** Preference key for smack debugging. */
    public static final String SMACK_DEBUG_KEY = "smack_debug";
    /** Preference key for full Jid for login. */
    public static final String FULL_JID_LOGIN_KEY = "full_jid_login";
    
    public ArrayList<HashMap<String, Object>> listItem = null;
    private boolean mIsConnected;
    private boolean mIsAccountConfigured;
    private boolean mPepEnabled;
    private boolean mIsBound = false;
    private SharedPreferences mSettings;
    private final PreferenceListener mPreferenceListener = new PreferenceListener();
    
	private ServiceConnection mConnection = new ContactsServiceConnection();
	private getcontacts serviceContacts;
	private Thread mthread;
	
	//数据库-表
	public DBConnection helper;
	public interface UserSchema {
		String TABLE_NAME = "Users";          //Table Name
//		String ID = "_id";                    //ID
		String USER_NAME = "user_name";       //User Name
//		String ADDRESS = "address";           //Address
		String TELEPHONE = "telephone";       //Phone Number
//		String MAIL_ADDRESS = "mail_address"; //Mail Address
		List<Map<String, Object>> MESSAGE_LIST = new ArrayList<Map<String, Object>>(2);
	}
	//////////////////////////增加消息到来时标志//////////////////////////////////////
	public  boolean mIsNewMessage = false;
	public  String mMessage = null;
	public  String mTopic = null;
	
    public miniApplication () {
    	
    }
    @Override
    public void onCreate() {
	super.onCreate();
	doBinderService();
	helper = new DBConnection(this);
	mSettings = PreferenceManager.getDefaultSharedPreferences(this);
	String login = mSettings.getString(miniApplication.ACCOUNT_USERNAME_KEY, "");
	String password = mSettings.getString(miniApplication.ACCOUNT_PASSWORD_KEY, "");
	mIsAccountConfigured = !("".equals(login) || "".equals(password));
	mSettings.registerOnSharedPreferenceChangeListener(mPreferenceListener);
	launchPushService();
    }

    @Override
    public void onTerminate() {
	super.onTerminate();
	Builder builder = new AlertDialog.Builder(this);
	builder.setTitle("onTerminate");
	builder.setMessage("被调用了");
	builder.setCancelable(true);
	builder.create().show();
	
	mSettings.unregisterOnSharedPreferenceChangeListener(mPreferenceListener);
	
	Intent svc = new Intent(this, MQTTService.class);
	stopService(svc);
    }
    public ArrayList<HashMap<String, Object>> getContactsData()
    {
    	return listItem;
    }
    /**
     * Tell if Mini is connected to a XMPP server.
     * @return false if not connected.
     */
    public boolean isConnected() {
	return mIsConnected;
    }

    /**
     * Set the status of the connection to a XMPP server of BEEM.
     * @param isConnected set for the state of the connection.
     */
    public void setConnected(boolean isConnected) {
	mIsConnected = isConnected;
    }

    /**
     * Tell if a XMPP account is configured.
     * @return false if there is no account configured.
     */
    public boolean isAccountConfigured() {
	return mIsAccountConfigured;
    }

    /**
     * Enable Pep in the application context.
     *
     * @param enabled true to enable pep
     */
    public void setPepEnabled(boolean enabled) {
	mPepEnabled = enabled;
    }

    /**
     * Check if Pep is enabled.
     *
     * @return true if enabled
     */
    public boolean isPepEnabled() {
	return mPepEnabled;
    }
    /**
     * A listener for all the change in the preference file. It is used to maintain the global state of the application.
     */
    private class PreferenceListener implements SharedPreferences.OnSharedPreferenceChangeListener {

	public PreferenceListener() {
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences  sharedPreferences, String key) {
	    if (miniApplication.ACCOUNT_USERNAME_KEY.equals(key) || miniApplication.ACCOUNT_PASSWORD_KEY.equals(key)) {
		String login = mSettings.getString(miniApplication.ACCOUNT_USERNAME_KEY, "");
		String password = mSettings.getString(miniApplication.ACCOUNT_PASSWORD_KEY, "");
		mIsAccountConfigured = !("".equals(login) || "".equals(password));
	    }
	}
    }//PreferenceListener
    
    /**
     * The service connection used to connect to the Beem service.
     */
    private class ContactsServiceConnection implements ServiceConnection {

    	public ContactsServiceConnection() {
    		
    	}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Toast toast = Toast.makeText(getApplicationContext(), "onServiceConnected", Toast.LENGTH_LONG);
			toast.show();
			serviceContacts = ((getcontacts.contactsBinder)service).getService();
			mthread = new Thread(mRunnable);
			mthread.start();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			serviceContacts = null;
		}		
    	
    };
    
    private void doBinderService ()
    {
    	Toast toast = Toast.makeText(getApplicationContext(), "doBinderService", Toast.LENGTH_LONG);
		toast.show();
    	miniApplication.this.startService(new Intent(miniApplication.this,getcontacts.class));
    	miniApplication.this.bindService(new Intent(miniApplication.this,  
    			getcontacts.class), mConnection, Context.BIND_AUTO_CREATE);
//    	miniApplication.this.startService(new Intent(miniApplication.this,miniService.class));
    	mIsBound = true;

    }
    private void launchPushService()
    {
        // Start the service
//    	TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
////    	String imei = tm.getDeviceId();
//    	String tel = tm.getLine1Number();
//        String mDeviceID = tel;
//        Toast toast = Toast.makeText(getApplicationContext(), mDeviceID, Toast.LENGTH_LONG);
//        toast.show();
//    	Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE).edit();
//    	editor.putString(PushService.PREF_DEVICE_ID, mDeviceID);
//    	editor.commit();
//    	PushService.actionStart(getApplicationContext());
    }
    public void doUnbindService() { 
        if (mIsBound) { 
            // Detach our existing connection. 
        	miniApplication.this.unbindService(mConnection);
        	serviceContacts.stopService(new Intent(miniApplication.this,getcontacts.class));
            mIsBound = false; 
        } 
    } 
    private Runnable mRunnable = new Runnable() {
    	public void run()
    	{
			listItem = serviceContacts.getData();
			sendBroadcast(new Intent(getcontacts.ACTION));
    	}
    };
    
    //建立存储收发短信数据库SQLite
    public static class DBConnection extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "MessageDB";
		private static final int DATABASE_VERSION = 1;
		private DBConnection(Context ctx) {
			super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		}
		public void onCreate(SQLiteDatabase db) {
			String sql = "CREATE TABLE " + UserSchema.TABLE_NAME + " (" 
			+ UserSchema.TELEPHONE  + " INTEGER primary key autoincrement, " 
			+ UserSchema.USER_NAME + " text not null, " 
			+ UserSchema.MESSAGE_LIST + " text not null "+ ");";
			
			db.execSQL(sql);	
		}
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub	
		}
	}
}